package com.tools;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.datahub.client.model.BlobRecordData;
import com.aliyun.datahub.client.model.RecordEntry;
import com.aliyun.datahub.clientlibrary.config.ProducerConfig;
import com.aliyun.datahub.clientlibrary.producer.Producer;
import com.bean.SignsDataBO;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class WXDatahubSingleton {
    Producer p;

    // 私有构造方法，防止外部直接实例化
    private WXDatahubSingleton() {
        ProducerConfig pConfig = new ProducerConfig(WXDatahubConfig.endpoint, WXDatahubConfig.accessId, WXDatahubConfig.accessKey);
        try{
            p = new Producer(WXDatahubConfig.projectName, WXDatahubConfig.topicName, pConfig);
        }catch (Exception e){
            System.out.println("Producer 初始化错误，请检查网络 ");
            e.printStackTrace();
        }

    }

    // 静态内部类，在加载时才初始化单例对象
    private static class SingletonHolder {
        private static final WXDatahubSingleton INSTANCE = new WXDatahubSingleton();
    }

    // 公共静态方法，返回单例对象
    public static WXDatahubSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    //发送Blob消息
    public  void sendBlob(List<String> dataList) {
        if(dataList.isEmpty()){
            return;
        }
        List<RecordEntry> list = new ArrayList<>();
        for (String str : dataList) {
            if (StringUtils.isNotBlank(str)) {
                try {
                    RecordEntry recordEntry = new RecordEntry();
                    BlobRecordData blobRecordData = new BlobRecordData
                            (str.getBytes(StandardCharsets.UTF_8));
                    recordEntry.setRecordData(blobRecordData);
                    list.add(recordEntry);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        p.send(list, 10);
    }


    //发送Blob消息
    public  List<String> generateBlobTOs(SignsDataBO... dataDTOS) {
        List<String> temp_list = new ArrayList<>();
        for (int i = 0; i < dataDTOS.length; i++) {
            String jsonString1 = JSONObject.toJSONString(dataDTOS[i]);
            System.out.println("第"+i+"条数据为:" + jsonString1);
            temp_list.add(jsonString1);
        }
        return temp_list;
    }


}